package com.wangfei.lecture;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

public class AnnotationTest {
    public static void main(String[] args) throws Exception {
        Person person = new Person();

        Class<Person> c = Person.class;
        Method method = c.getMethod("somebody", new Class[]{String.class, int.class});
        method.invoke(person, new Object[]{"lily", 18});
        iteratorAnnotations(method);

        Method empty = c.getMethod("empty", new Class[]{});
        empty.invoke(person);
        iteratorAnnotations(empty);
    }

    public static void iteratorAnnotations(Method method) {
        if (method.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
            String[] values = myAnnotation.value();
            for (String str : values) {
                System.out.print(str + ", ");
            }
            System.out.println();
        }

        // 获取方法上的所有注解
        Annotation[] annotations = method.getAnnotations();
        for(Annotation annotation : annotations) {
            System.out.println(annotation);
        }

    }
}

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String[] value() default "unknown";
}

class Person {

    @MyAnnotation
    @Deprecated
    public void empty() {
        System.out.println("\nempty");
    }
    @MyAnnotation(value = {"girl", "body"})
    public void somebody(String name, int age) {
        System.out.println("\nsomebody: " + name + ", " + age);
    }
}